package com.chess.mvc.login;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.chess.db.bean.User;
import com.chess.db.cache.UserCache;
import com.chess.manager.GameServerManager;
import com.chess.manager.LoginTokenManager;
import com.chess.protobuf.EchoMsg.GameServerRegisterRequest;
import com.jfinal.core.Controller;
import com.sojoys.artifact.annotation.IController;

/**
 * @author : DengYing
 * @CreateDate : 2017年4月10日 下午8:32:23
 * @Description ：Please describe this document
 */

@IController("/login")
public class LoginController extends 	BaseController{
	/**
	 * 登陆
	 */
	public void index() {
		String code = getPara("code");
		String channel = getPara("channel");
		String name = getPara("name");
		String deviceId = getPara("deviceId");
		String deviceName = getPara("deviceName");
		String deviceToken = getPara("deviceToken");
		String osName = getPara("osName");
		String osVersion = getPara("osVersion");
		String sdkName = getPara("sdkName");
		String sdkVersion = getPara("sdkVersion");
		String mcc = getPara("mcc");
//		GameServerRegisterRequest gameinfo = GameServerManager.getGameServer();
//		System.out.println(gameinfo == null ? "null":gameinfo.getAddress());
		if (code==null 
			|| channel==null
			|| name==null
			|| deviceId==null
			|| deviceName==null
			|| deviceToken==null
			|| osName==null
			|| osVersion==null
			|| sdkName==null
			|| sdkVersion==null
			|| mcc==null) {
			renderError("参数错误");
			return;
		}
		User user = UserCache.getInstance().getByCodeChannel(code, channel);
		Date dateNow = new Date(); 
		if (user==null) {
			user = new User("", code, channel, name, deviceId, deviceName, deviceToken, osName, osVersion, sdkName, sdkVersion, mcc, dateNow, dateNow, dateNow);
			user = user.insert();
		}else {
			user.setLastLoginDate(dateNow);
			user = user.update();
		}
		Map<String, String> map = new HashMap<>();
		GameServerRegisterRequest gameinfo = GameServerManager.getGameServer();
		String token = UUID.randomUUID().toString();
		// 添加 || 更新 token
		LoginTokenManager.addCache(user.getId(),token);
		map.put("token", token);
		map.put("address", gameinfo == null ? "null":gameinfo.getAddress());
		renderSuccess(map, "");
	}
	
	/**
	 * 验证Token
	 */
	public void checkToken(){
		String token = getPara("token");
		if (token!=null) {
			String uid = LoginTokenManager.removeToken(token);
			if (uid!=null) {
				User user = UserCache.getInstance().getById(uid);
				if (user!=null) {
					renderSuccess(user.toJson(), "");
					return;
				}
			}
		}
		renderError("token 验证失败");
	}
}
